package md.rdcrng.cvs;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;

/**
 <p/>
 @author Radu Creanga <radu.creanga@concensus.com>
 */
class Components implements Serializable {

    private final ConcurrentMap<Contextual<?>, Component<?>> components = new ConcurrentHashMap<>();

    protected <T> T create(Contextual<T> contextual, CreationalContext<T> creationalContext) {
        Component<T> component = new Component<>(contextual, creationalContext);
        this.components.put(contextual, component);
        return component.getInstance();
    }

    @SuppressWarnings("unchecked")
    protected <T> T get(Contextual<T> contextual) {
        Component<?> component = this.components.get(contextual);
        return (T) (component == null ? null : component.getInstance());
    }

    protected void destroy() {
        for (Component<?> component : this.components.values()) {
            component.destroy();
        }
    }

}
